#!/bin/sh
#
# Copyright 2018-2021 Balena Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit

. /usr/sbin/balena-config-vars

echo "Rollback: Running tests"

# VPN health check
if [ -f /mnt/state/rollback-health-variables ]; then
	. /mnt/state/rollback-health-variables
	if [ -f /run/openvpn/vpn_status/active ]; then
		echo "Rollback: VPN is back online in new OS."
	elif [ $BALENAOS_ROLLBACK_VPNONLINE == 1 ]; then
		echo "Rollback: ERROR: VPN used to be ok but has not connected!"
		exit 1
	elif [ $BALENAOS_ROLLBACK_VPNONLINE == 0 ]; then
		echo "Rollback: VPN used to be offline before HUP. Not using VPN healthcheck for rollback"
	fi
fi

# balenaEngine health check
if /usr/lib/balena/balena-healthcheck ; then
	echo "Rollback: balenaEngine looks healthy"
else
	echo "Rollback: ERROR: balenaEngine is not healthy!"
	exit 1
fi

# The following script can be overriden by device integration
# repositories with board specific healthchecks
echo "Rollback: Running board specific healthchecks..."
if /usr/bin/rollback-board-healthcheck ; then
	echo "Rollback: No issues detected."
else
	echo "Rollback: ERROR: Board specific healthchecks failed!"
	exit 1
fi
